import yaml
import hashlib
from os import listdir
from time import sleep
from os.path import dirname, isdir, isfile
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


class ToolMan:
    __config = None

    @classmethod
    def get_config(cls):
        if cls.__config is None:
            with open(dirname(dirname(__file__)) + '/app.yml', encoding='utf-8') as fp:
                yml = fp.read()
            cls.__config = yaml.safe_load(yml)
        return cls.__config


def config(key=None, default=None):
    cfg = ToolMan.get_config()
    if key is None:
        return cfg
    need = key.split('.')
    for field in need:
        if cfg and field in cfg:
            cfg = cfg[field]
        else:
            cfg = None
    if cfg is not None:
        return cfg
    return default


def scan_videos(videos_dir, suffix=None):
    def __scan(base_dir):
        f_list = listdir(base_dir)
        for f in f_list:
            nf = base_dir + '\\' + f
            if isdir(nf):
                __scan(nf)
            if isfile(nf) and f.split('.')[-1].lower() in suffix:
                videos.append(nf)

    videos = []
    if suffix is None:
        suffix = ['avi', 'mp4', 'wmv', 'mkv', 'rmvb', 'ts']
    __scan(videos_dir)
    return videos


def node_xpath(node, path, idx=0, callback=None):
    arr = node.xpath(path)
    if len(arr) >= idx + 1:
        if callback is not None:
            return callback(arr[idx])
        return arr[idx].strip()
    return None


def md5(content):
    return hashlib.md5(content.encode('utf-8')).hexdigest()


if '__main__' == __name__:
    r = config('test.b.c')
    print(r)
    Browser().get('https://www.baidu.com/')
    sleep(2)
    Browser().get('https://www.baidu.com/')
    sleep(5)
